package com.sclimin.pickerview;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import androidx.core.view.ViewCompat;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Interpolator;

import java.util.ArrayList;

/**
 * 作者：limin
 * <p>
 * 创建时间：2019/1/23
 */
public class PickerView extends View {

    private static final String TAG = PickerView.class.getSimpleName();

    /**
     * 可视Item个数（2n + 1，设定为奇数），个人觉得9个比较合适
     */
    private static final int VISIBLE_ITEM_COUNT;
    private static final int VISIBLE_ITEM_MIDDLE_COUNT;

    private static final Interpolator sQuinticInterpolator;

    static {
        VISIBLE_ITEM_COUNT = 9;
        VISIBLE_ITEM_MIDDLE_COUNT = (VISIBLE_ITEM_COUNT + 1) / 2;

        sQuinticInterpolator = t -> {
            --t;
            return t * t * t * t * t + 1.0F;
        };
    }

    private PickerAdapter mAdapter;

    private final Paint mPaint;

    private int mOffset;

    private ArrayList<Element> mElements;

    private int mItemHeight;

    private Rect mRect = new Rect();

    private float mRollerRadius;

    private final Rect mContentBounds = new Rect();

    public PickerView(Context context) {
        this(context, null);
    }

    public PickerView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public PickerView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(Color.RED);

        mItemHeight = (int) (getResources().getDisplayMetrics().density * 32);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = mItemHeight * VISIBLE_ITEM_COUNT;

        mContentBounds.set(ViewCompat.getPaddingStart(this), getPaddingTop(),
                width - ViewCompat.getPaddingStart(this),
                height - getPaddingBottom());

        // TODO 初始化与View大小相关的参数
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.save();
        canvas.translate(mContentBounds.left, mContentBounds.centerY());

        mRect.set(0, 0, mContentBounds.width(), mItemHeight);
        mRect.offset(0, 0 - mRect.centerY());

        mPaint.setColor(0x80ff0000);
        canvas.drawRect(mRect, mPaint);

        mPaint.setColor(0x8000ff00);
        canvas.scale(0.9f, 0.9f, mRect.centerX(), mRect.centerY());
        canvas.drawRect(mRect, mPaint);

        canvas.restore();
    }
}
